package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存击穿解决封装方法
     * @param keyPrefix key前缀
     * @param id  业务id
     * @param type 返回的实体类类型
     * @param dbFallback 通过数据库查询方法
     * @param time 过期时间
     * @param unit 过期类型
     * @param <R> 实体类泛型
     * @param <ID> id的类型泛型
     * @return
     */
    public <R,ID> R queryWithPassThrough(String keyPrefix ,
                                         ID id ,
                                         Class<R> type,
                                         Function<ID,R> dbFallback,
                                         Long time,
                                         TimeUnit unit){
        //1.从redis中查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3存在直接返回
            return JSONUtil.toBean(json, type);
        }
        // 判断命中的是否是空值
        if (json != null){
            return null;
        }
        //4不存在根据id查询数据库
        R r = dbFallback.apply(id);
        if (r == null){
            //将空值写入redis
            this.set(key,"",time, unit);
            //5不存在，返回错误
            return null;
        }
        //6存在，吧数据写入redis中
        this.set(key,JSONUtil.toJsonStr(r),time, unit);
        //7返回
        return r;
    }

    /**
     * 创建一个线程池，去执行缓存重建
     * @param id
     * @return
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期解决缓存击穿问题封装方法
     * @param ketPrefix
     * @param id
     * @param type
     * @param dbFallBack
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R,ID> R queryWithLogicalExpire(String ketPrefix,
                                           ID id,
                                           Class<R> type,
                                           Function<ID,R> dbFallBack,
                                           Long time,
                                           TimeUnit unit){
        //1.从redis中查询商铺缓存
        String key = ketPrefix+id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            //3不存在直接返回
            return null;
        }
        //4命中.需要把JSon反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        //5判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){
            //5.1未过期，直接返回店铺信息
            return r;
        }
        //5.2过期，需要缓存重建
        //6缓存重建
        //6.1获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = this.tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (isLock) {
            //6.3成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()-> {

                    try {
                        //重建缓存先查数据库然后再写入redis
                        R r1 = dbFallBack.apply(id);
                        this.setWithLogicalExpire(key,r1,time,unit);

                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }finally {
                        //释放锁
                        unLock(lockKey);
                    }
            });
        }
        //6.4返回过期的商铺信息，
        return r;
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
